
import path from 'path'
import fs from 'fs-extra'
import inquirer from 'inquirer'
import ini from 'ini'
import _ from 'lodash'
import ora from 'ora'
import { GMC_CONF, GMC_PATH, GMC_CONFILE, getProjectList, getSocketList } from './base'

export default () => {
  let project = null
  let projectList = getProjectList()
  if (projectList.length === 0) {
    console.log(`\n   还没有项目建立，先去创建一个 !\n`)
    return
  }
  return inquirer.prompt([
    {
      type: 'list',
      name: 'project',
      message: '选择一个项目 ?',
      choices: projectList
    }
  ])
  .then( ret => {
    project = ret.project.replace(/(\[)([a-zA-Z]+)(\])(\s)(\-){2}(\s)(\S+)/, '$2')
    return inquirer.prompt([
      {
        type: 'list',
        name: 'option',
        message: 'Socket连接配置选项 ?',
        choices: [
          {
            key: '0',
            name: '1) 添加Socket连接',
            value: 'create'
          },
          {
            key: '1',
            name: '2) 修改Socket连接',
            value: 'edit'
          },
          {
            key: '2',
            name: '3) 删除Socket连接',
            value: 'remove'
          },
        ]
      }
    ])
  })
  .then( ret => {
    switch (ret.option) {
      case 'create': {
        return addSocket(project)
      }
      case 'edit': {
        return editSocket(project)
      }
      case 'remove': {
        return removeSocket(project)
      }
      default:
        break
    }
  })
}

const addSocket = (project) => {
  let projectConf = GMC_CONF[project]
  let socketConf = projectConf.socket || {}
  return inquirer.prompt([
    {
      type: 'input',
      name: 'socket',
      message: 'Socket连接标志 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '连接标志不能为空 !'
        }
        if (!/[0-9a-zA-Z\-\_]/.test(value)) {
          return '连接标志格式错误，必须是数字、英文字母或下划线组成 !'
        }
        if (_.has(socketConf, value)) {
          return '连接标志已存在，此项不能重名 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'name',
      message: 'Socket连接名称 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '连接名称不能为空 !'
        }
        if (!/[0-9a-zA-Z\-\_\u4e00-\u9fa5]/.test(value)) {
          return '连接名称格式错误，必须是数字、英文字母、下划线或中文组成 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'rtsp',
      message: 'Socket连接地址 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '连接地址不能为空 !'
        }
        return true
      }
    }
  ])
  .then( ret => {
    let newConf = {
      ...GMC_CONF,
      [project]: {
        ...projectConf,
        ['socket']: {
          ...socketConf,
          [ret.socket]: _.omit(ret, ['socket'])
        }
      }
    }
    console.log('')
    let spinner = ora(`    Create Socket Connection ...`).start()
    fs.writeFileSync(GMC_CONFILE, ini.stringify(newConf, { whitespace: true }), 'utf-8')
    setTimeout(() => {
      spinner.stop()
      console.log('✔   Complete Create Socket Connection !\n')
    }, 500)
  })
}

const editSocket = (project) => {
  let socket = null
  let projectConf = GMC_CONF[project]
  let socketConf = projectConf.socket || {}
  let socketList = getSocketList(project)
  if (socketList.length === 0) {
    console.log(`\n   还没有Socket连接 !\n`)
    return
  }
  return inquirer.prompt([
    {
      type: 'list',
      name: 'socket',
      message: '选择一个Socket连接 ?',
      choices: socketList
    }
  ])
  .then( ret => {
    socket = ret.socket.replace(/(\[)([a-zA-Z]+)(\])(\s)(\-){2}(\s)(\S+)(\s)(\-){2}(\s)(\S+)/, '$2')
    return inquirer.prompt([
      {
        type: 'input',
        name: 'name',
        message: 'Socket连接名称 ?',
        default: socketConf[socket].name,
        validate: value => {
          if (_.isEmpty(_.trim(value))) {
            return '连接名称不能为空 !'
          }
          if (!/[0-9a-zA-Z\-\_\u4e00-\u9fa5]/.test(value)) {
            return '连接名称格式错误，必须是数字、英文字母、下划线或中文组成 !'
          }
          return true
        }
      },
      {
        type: 'input',
        name: 'rtsp',
        message: 'Socket连接地址 ?',
        default: socketConf[socket].rtsp,
        validate: value => {
          if (_.isEmpty(_.trim(value))) {
            return '连接地址不能为空 !'
          }
          return true
        }
      }
    ])
  })
  .then( ret => {
    let newConf = {
      ...GMC_CONF,
      [project]: {
        ...projectConf,
        ['socket']: {
          ...socketConf,
          [socket]: ret
        }
      }
    }
    console.log('')
    let spinner = ora(`    Edit Socket Connection ...`).start()
    fs.writeFileSync(GMC_CONFILE, ini.stringify(newConf, { whitespace: true }), 'utf-8')
    setTimeout(() => {
      spinner.stop()
      console.log('✔   Complete Edit Socket Connection !\n')
    }, 500)
  })
}

const removeSocket = (project) => {
  let projectConf = GMC_CONF[project]
  let socketConf = projectConf.socket || {}
  let socketList = getSocketList(project)
  if (socketList.length === 0) {
    console.log(`\n   还没有Socket连接 !\n`)
    return
  }
  return inquirer.prompt([
    {
      type: 'checkbox',
      name: 'socket',
      message: '选择一个Socket连接 ?',
      choices: socketList
    }
  ])
  .then( ret => {
    if (ret.socket.length === 0) {
      console.log(`\n   您没有选择任何连接 !\n`)
      return
    }
    console.log('')
    let spinner = ora(`    Remove Socket Connection ...`).start()
    let newSocketConf = socketConf
    for (let item of ret.socket) {
      let socket = item.replace(/(\[)([a-zA-Z]+)(\])(\s)(\-){2}(\s)(\S+)(\s)(\-){2}(\s)(\S+)/, '$2')
      _.unset(newSocketConf, socket)
    }
    let newConf = {
      ...GMC_CONF,
      [project]: {
        ...projectConf,
        ['socket']: newSocketConf
      }
    }
    fs.writeFileSync(GMC_CONFILE, ini.stringify(newConf, { whitespace: true }), 'utf-8')
    setTimeout(() => {
      spinner.stop()
      console.log('✔   Complete Remove Socket Connection !\n')
    }, 500)
  })
}